using System;
using System.Data;
using System.Configuration;
using System.Web.Security;
using sbMembership.Library.Domain;
using sbMembership.Library.Presenters.ViewInterfaces;

namespace sbMembership.Library.Presenters
{
    public class AddUserPresenter
    {
        private IAddUserView view;

        public AddUserPresenter(IAddUserView view)
        {
            if (view == null) throw new ArgumentNullException("view may not be null");

            this.view = view;
        }

        public EventHandler CancelAddEvent;
        public EventHandler AddUserCompleteEvent;

        public void InitView()
        {
            view.Message = "Use this form to add a new user.";
            view.ResetForm();
        }

        public void AddUser(bool isPageValid)
        {
            if (! isPageValid)
            {
                view.Message = "There was a problem with your inputs.  Make sure you supplied everything and try again.";
                return;
            }

            if (!IsDuplicateOfExisting(view.UserToAdd))
            {
                Membership.CreateUser(view.UserToAdd.UserName, view.UserToAdd.Password, view.UserToAdd.Email);
                AddUserCompleteEvent(this, null);
            }
            else
                view.Message = "The ID you provided is already in use.";

        }

        private bool IsDuplicateOfExisting(sbUser newUser)
        {
            try
            {
                MembershipUser duplicateUser = Membership.GetUser(newUser.UserName, false);
                return duplicateUser != null;
            }
            catch
            {
                return false;
            }
        }

        public void CancelAdd()
        {
            CancelAddEvent(this, null);
        }
    }
}
